//
//  AppDelegate.m
//  meiang_edu
//
//  Created by hfcb on 2018/7/29.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "AppDelegate.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "MATabBarViewController.h"
#import "ChaosNewFeatureController.h"
#import "AppDelegate+LaunchAd.h"
#import "UIWindow+Extension.h"
UIColor *MainNavBarColor = nil;
UIColor *MainViewColor = nil;



// 引入 JPush 功能所需头文件
#import "JPUSHService.h"
#import <UserNotifications/UserNotifications.h>
#import <AdSupport/AdSupport.h>
static NSString *appKey = @"b16064983b8d888d1eb89c9f";
static NSString *channel = @"App Store";
static BOOL isProduction = YES;

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self setupKeyBoardMgr];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    // 1.从沙盒中获取旧的版本号
    NSString *oldVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"CFBundleVersion"];
    // 2.获取新的版本号
    NSString *newVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleVersion"];
    if ([oldVersion isEqualToString:newVersion])
    {
        // 版本号相同,不显示新界面
        MATabBarViewController *tabBarVC = [[MATabBarViewController alloc] init];
        self.window.rootViewController = tabBarVC;
        [self setupXHLaunchAd]; // 版本号相同,显示广告
    }
    else
    {
        // 版本号不相同,显示新特性,并存储版本号到沙盒
        ChaosNewFeatureController *newFeatureVC = [[ChaosNewFeatureController alloc] init];
        self.window.rootViewController = newFeatureVC;
        // 3.将新的版本号存储
        [[NSUserDefaults standardUserDefaults] setObject:newVersion forKey:@"CFBundleVersion"];
    }
    [self.window makeKeyAndVisible];
    // 导航栏设置
    [self setNavBarAppearence];
    [self getStsToken];
    
#pragma mark   极光推送
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    // 3.0.0及以后版本注册
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0)
    {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        if (@available(iOS 10.0, *))
        {
            entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        }
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    else
    {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:1
            advertisingIdentifier:advertisingId];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID)
    {
        if(resCode == 0)
        {
            DLog(@"registrationID获取成功：%@",registrationID);
        }
        else
        {
            DLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    return YES;
}

#pragma mark 极光推送代码开始

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [JPUSHService registerDeviceToken:deviceToken];
}


- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    DLog(@"111");
}


// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification
{
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        //从通知界面直接进入应用
        DLog(@"从通知界面直接进入应用");
    }
    else
    {
        //从通知设置界面进入应用
        DLog(@"从通知界面直接进入应用1");
    }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler
{
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}

#pragma mark  极光推送代码结束

- (void)setupKeyBoardMgr
{
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    keyboardManager.enable = YES; // 控制整个功能是否启用
    keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
    keyboardManager.shouldToolbarUsesTextFieldTintColor = YES; // 控制键盘上的工具条文字颜色是否用户自定义
    keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews; // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
    keyboardManager.enableAutoToolbar = YES; // 控制是否显示键盘上的工具条
    keyboardManager.shouldShowToolbarPlaceholder = YES; // 是否显示占位文字
    keyboardManager.placeholderFont = [UIFont boldSystemFontOfSize:17]; // 设置占位文字的字体
    keyboardManager.keyboardDistanceFromTextField = 10.0f; // 输入框距离键盘的距离
}

- (void)setNavBarAppearence
{
    MainNavBarColor = PROJECT_DEFAULT_COLOR;
    MainViewColor   = [UIColor colorWithRed:126/255.0 green:126/255.0 blue:126/255.0 alpha:1];
    
    // 设置是 广泛使用WRNavigationBar，还是局部使用WRNavigationBar，目前默认是广泛使用
    [WRNavigationBar wr_widely];
    [WRNavigationBar wr_setBlacklist:@[@"SpecialController",
                                       @"TZPhotoPickerController",
                                       @"TZGifPhotoPreviewController",
                                       @"TZAlbumPickerController",
                                       @"TZPhotoPreviewController",
                                       @"TZVideoPlayerController"]];
    
    // 设置导航栏默认的背景颜色
    [WRNavigationBar wr_setDefaultNavBarBarTintColor:MainNavBarColor];
    // 设置导航栏所有按钮的默认颜色
    [WRNavigationBar wr_setDefaultNavBarTintColor:[UIColor whiteColor]];
    // 设置导航栏标题默认颜色
    [WRNavigationBar wr_setDefaultNavBarTitleColor:[UIColor whiteColor]];
    // 统一设置状态栏样式
    [WRNavigationBar wr_setDefaultStatusBarStyle:UIStatusBarStyleLightContent];
    // 如果需要设置导航栏底部分割线隐藏，可以在这里统一设置
    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)getStsToken
{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [MBManager showLoading];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request)
    {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@", GetStsToken_URL];
        request.methodType = ZBMethodTypePOST;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type)
    {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1)
        { // 请求成功
            [MBManager hideAlert];
            NSDictionary *dict = dataDict[@"value"];
            //oss的一些信息
            [ZOSSFileUploader shareInstance].dicInfoOSS = dict;
        }
        else
        {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error)
    {
        DLog(@"%@",error);
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache)
    {
        if (isCache==YES)
        {
            DLog(@"使用了缓存");
        }
    }];
}

@end
